﻿' --- Copyright (c) notice NevoWeb ---
'  Copyright (c) 2008 SARL NevoWeb.  www.nevoweb.com. All rights are reserved.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice --- 


Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized

Namespace NEvoWeb.Modules.NB_Store.Gateway

    Public Class GatewayPayBox
        Inherits GatewayInterface

        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo
            objSInfo = objSCtrl.GetSetting(PortalID, "PayBox.gateway", Lang)

            If Not objSInfo Is Nothing Then
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                strHTML = "<INPUT TYPE=IMAGE NAME=PAYBOX BORDER=0 SRC=""" & setParams("ButtonImageURL") & """/>"

            End If

            Return strHTML
        End Function


        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1
            Dim rtnMsg As String = ""
            Dim AuthCode As String = ""
            Dim ErrCode As String = ""

            'get authorization, if exists
            If Not Request.QueryString("auto") Is Nothing Then
                AuthCode = Request.QueryString("auto")
            End If

            ordID = Request.QueryString("maref")
            ErrCode = Request.QueryString("erreur")

            'set rtnMsg to security error message
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
            rtnMsg = objSInfo.SettingText

            UpdateLog("AUTO: PayPox rawurl: " & Request.RawUrl)

            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    UpdateLog("AUTO: PayPox Start. OrdID:" & ordID & " AuthCode: " & AuthCode & " ErrCode: " & ErrCode)
                    If AuthCode = "" Or ErrCode <> "00000" Then
                        'Authorization does NOT exist, therefore payment must have FAILED.
                        ' check if order has already been processed
                        If Not objOInfo.OrderIsPlaced Then
                            'check if order has already been cancelled
                            If Not objOInfo.OrderStatusID = 30 Then
                                'remove qty in trans
                                objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                'set order status to cancelled
                                objOInfo.OrderStatusID = 30
                                objOCtrl.UpdateObjOrder(objOInfo)
                            End If
                        End If
                    Else
                        'Authorization exists, therefore payment must have worked.
                        ' check if order has already been processed
                        If Not objOInfo.OrderIsPlaced Then
                            'remove qty in trans
                            objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                            'set order status to Payed
                            objOInfo.OrderStatusID = 40
                            Dim intUserId As Integer = objOInfo.UserID
                            If intUserId < 0 Then intUserId = 0
                            objOInfo.OrderNumber = Format(PortalID, "00") & "-" & intUserId.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                            objOInfo.OrderIsPlaced = True
                            objOCtrl.UpdateObjOrder(objOInfo)
                            SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", GetCurrentCulture)
                            SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")
                        End If
                    End If
                End If
            End If

        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1
            Dim rtnMsg As String = ""
            Dim AuthCode As String = ""
            Dim ErrCode As String = ""

            'get authorization, if exists
            If Not Request.QueryString("auto") Is Nothing Then
                AuthCode = Request.QueryString("auto")
            End If

            ordID = Request.QueryString("maref")
            ErrCode = Request.QueryString("erreur")

            'set rtnMsg to security error message
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
            rtnMsg = objSInfo.SettingText
            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    If objOInfo.UserID = UserID Then
                        If AuthCode = "" Or ErrCode <> "00000" Then
                            'Authorization does NOT exist, therefore payment must have FAILED.
                            ' check if order has already been processed
                            If Not objOInfo.OrderIsPlaced Then
                                'check if order has already been cancelled
                                If Not objOInfo.OrderStatusID = 30 Then
                                    'remove qty in trans
                                    objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                    'set order status to cancelled
                                    objOInfo.OrderStatusID = 30
                                    objOCtrl.UpdateObjOrder(objOInfo)
                                End If
                                'set Cancel order message
                                objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentFAIL.text", GetCurrentCulture)
                                rtnMsg = objSInfo.SettingText
                            End If
                        Else
                            'Authorization exists, therefore payment must have worked.
                            ' check if order has already been processed or cancelled
                            If Not objOInfo.OrderIsPlaced And objOInfo.OrderStatusID <> 30 Then
                                'remove qty in trans
                                objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                'set order status to Payed
                                objOInfo.OrderStatusID = 45
                                Dim intUserId As Integer = objOInfo.UserID
                                If intUserId < 0 Then intUserId = 0
                                objOInfo.OrderNumber = Format(PortalID, "00") & "-" & intUserId.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                objOInfo.OrderIsPlaced = True
                                objOCtrl.UpdateObjOrder(objOInfo)
                                SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", GetCurrentCulture)
                                SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")
                            End If
                            'set completed order message
                            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", GetCurrentCulture)
                            rtnMsg = objSInfo.SettingText
                        End If

                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
            End If
            Return rtnMsg
        End Function

        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if Paypal button has been clicked
            If Not Request.Form.Item("PAYBOX.x") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)

            Dim RPost As New RemotePost

            'test if Paypal button has been clicked
            If Not Request.Form.Item("PAYBOX.x") Is Nothing Then
                Dim objSCtrl As New SettingsController
                Dim objSInfo As NB_Store_SettingsInfo
                objSInfo = objSCtrl.GetSetting(PortalID, "PayBox.gateway", "None")
                If Not objSInfo Is Nothing Then

                    Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                    Dim PayPalButtonURL As String = setParams("ButtonImageURL")
                    Dim execpath As String = setParams("execpath")

                    Dim objOCtrl As New OrderController
                    Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)

                    If Not oInfo Is Nothing Then

                        Dim prm As String = ""
                        Dim de As DictionaryEntry

                        For Each de In setParams
                            If de.Key.ToString.StartsWith("PBX_") Then
                                prm = prm & " " & de.Key.ToString & "=" & de.Value.ToString
                            End If
                        Next

                        prm = Replace(prm, "[ORDERID]", oInfo.OrderID.ToString)
                        prm = Replace(prm, "[TRANSID]", oInfo.OrderID.ToString("00000"))
                        prm = Replace(prm, "[ORDERNUMBER]", oInfo.OrderNumber.ToString)
                        prm = Replace(prm, "[ORDERAMOUNT]", Replace(Replace(oInfo.Total.ToString("0.00"), ".", ""), ",", ""))
                        prm = Replace(prm, "[CUSTOMERID]", oInfo.UserID.ToString)
                        prm = Replace(prm, "[LANGUAGE]", Left(Lang, 2))
                        prm = Replace(prm, "[PROMOCODE]", oInfo.PromoCode)
                        prm = Replace(prm, "[CARTID]", CurrentCart.GetCurrentCart(PortalID).CartID)
                        prm = Replace(prm, "[CURRENTCULTURE]", Lang)
                        If oInfo.Email.ToString <> "" Then
                            prm = Replace(prm, "[CUSTOMEREMAIL]", oInfo.Email.ToString)
                        Else
                            Dim uInfo As DotNetNuke.Entities.Users.UserInfo
                            uInfo = DotNetNuke.Entities.Users.UserController.GetUser(PortalID, oInfo.UserID, True)
                            If Not uInfo Is Nothing Then
                                prm = Replace(prm, "[CUSTOMEREMAIL]", DotNetNuke.Entities.Users.UserController.GetUser(PortalID, oInfo.UserID, True).Email)
                            Else
                                prm = Replace(prm, "[CUSTOMEREMAIL]", GetMerchantEmail(PortalID))
                            End If
                        End If

                        Dim strResult As String = GetProcessText(execpath, prm, "")

                        'update stock tranction in progress
                        Dim objPCtrl As New ProductController
                        objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)

                        'set order status to redirect to bank
                        oInfo.OrderStatusID = 20
                        objOCtrl.UpdateObjOrder(oInfo)

                        objSInfo = objSCtrl.GetSetting(PortalID, "gateway.loadimage", "None")

                        'RPost = New RemotePost
                        'RPost.Url = payPalURL

                        Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)
                        'objCInfo.BankHtmlRedirect = RPost.GetPostHtml(objSInfo.SettingValue)
                        objCInfo.BankHtmlRedirect = strResult
                        CurrentCart.Save(objCInfo)

                        UpdateLog("PayPox URL = " & strResult)

                    End If
                End If
            End If
        End Sub

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

        Private Function GetActionUrl(ByVal message As String) As String
            Dim StartPos As Integer
            Dim EndPos As Integer
            Dim PayBoxAct As String

            If message = "" Then
                PayBoxAct = "No PayBox message returned from API"
            Else
                StartPos = message.IndexOf("""")
                EndPos = message.IndexOf("""", StartPos + 1)
                PayBoxAct = message.Substring(StartPos + 1, ((EndPos - StartPos) - 1))
            End If

            Return PayBoxAct

        End Function

        Shared Function GetProcessText(ByVal process As String, ByVal param As String, ByVal workingDir As String) As String
            Dim p As Process = New Process
            ' this is the name of the process we want to execute
            p.StartInfo.FileName = process
            If Not (workingDir = "") Then
                p.StartInfo.WorkingDirectory = workingDir
            End If
            p.StartInfo.Arguments = param
            ' need to set this to false to redirect output
            p.StartInfo.UseShellExecute = False
            p.StartInfo.RedirectStandardOutput = True
            ' start the process
            p.Start()
            ' read all the output
            ' here we could just read line by line and display it
            ' in an output window
            Dim output As String = p.StandardOutput.ReadToEnd
            ' wait for the process to terminate
            p.WaitForExit()
            Return output
        End Function

    End Class


End Namespace

